<template>
  <div v-if="!node_list.length">该服务企业并未配置项目文件</div>
  <div class="flex">
    <div v-for="(item, index) in node_list" :key="item.id">
      <div
        :class="node_index == index ? 'top_title_select' : ''"
        class="top_title"
        v-if="type == 5"
        @click="
          (node_index = node_index != index ? index : node_index), (node_item = item);
        "
      >
        {{
          type_list.filter((i) => {
            return i.type == item.type;
          })[0].label
        }}
      </div>
    </div>
  </div>
  <el-divider v-show="type == 5"></el-divider>
  <div v-if="type == 5" style="height: calc(100% - 60px); overflow-y: auto">
    <div
      class="m_top10"
      v-for="item in node_index == 1
        ? taskOrder_list
        : node_index == 2
        ? requireChange_list
        : ['']"
    >
      <div v-if="node_index == 1" class="fw">
        <span v-if="item.type == 1">首次提交</span>
        <span v-if="[2, 3, 4].includes(item.type)">
          <span v-if="item.type == 2">设计变更</span>
          <span v-if="item.type == 3">需求变更</span>
          <span v-if="item.type == 4">现场返工</span>

          <span v-for="item1 in requireChange_list" :key="item1.id">
            <span v-if="item.changeId == item1.id"> 关联变更代号：{{ item1.code }}</span>
          </span>
        </span>
      </div>
      <div v-if="node_index == 2" class="fw">
        <span>变更代号：{{ item.code }}</span>
      </div>

      <el-table
        :data="
          task_file_list.filter((i) => {
            return i.type == node_index + 1 && (!i.sourceId || i.sourceId == item.id);
          })
        "
        border
        @expand-change="expandChange"
        row-key="id"
        :expand-row-keys="expands"
        class="m_top10"
        max-height="700"
      >
        <el-table-column type="expand">
          <template #default="props">
            <el-table
              border
              :data="props.row.recordList"
              style="margin: 2%; width: 96%"
              max-height="400"
            >
              <el-table-column
                label="上传人"
                prop="updateByName"
                width="150"
              ></el-table-column>
              <el-table-column label="updateTime" width="200">
                <template #default="scope">
                  <div v-if="scope.row.updateTime">
                    {{ formatDate(Number(scope.row.updateTime), "YYYY-MM-DD hh:mm:ss") }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="名称">
                <template #default="scope">
                  <a
                    class="table_file"
                    @click="
                      download_file({
                        url: scope.row.newUrl,
                        fileName: scope.row.newName,
                      })
                    "
                  >
                    {{ scope.row.newName }}
                  </a>
                </template>
              </el-table-column>
              <el-table-column label="操作类型" width="200">
                <template #default="scope">
                  <div v-if="scope.row.type == 1">新增</div>
                  <div v-if="scope.row.type == 2">覆盖</div>
                  <div v-if="scope.row.type == 3">删除</div>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="文件类别" prop="name">
          <template #default="scope">
            <div v-for="item1 in file_list" :key="item1.id">
              <span v-if="scope.row.fileConfigId == item1.id">{{ item1.name }}</span>
            </div>
          </template></el-table-column
        >
        <el-table-column label="名称">
          <template #default="scope">
            <a
              class="table_file"
              @click="
                download_file({
                  url: scope.row.url,
                  fileName: scope.row.fileName,
                })
              "
            >
              {{ scope.row.fileName }}
            </a>
          </template>
        </el-table-column>
        <el-table-column label="上传时间">
          <template #default="scope">
            <div v-if="scope.row.updateTime">
              {{ formatDate(Number(scope.row.updateTime), "YYYY-MM-DD hh:mm:ss") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="上传人" prop="updateByName" width="120"></el-table-column>
        <el-table-column label="文件类型限制" prop="accept">
          <template #default="scope">
            <div v-for="item1 in file_list" :key="item1.id">
              <span v-if="scope.row.fileConfigId == item1.id">{{
                item1.fileTypeList
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="文件大小限制">
          <template #default="scope">
            <div v-for="item1 in file_list" :key="item1.id">
              <div v-if="scope.row.fileConfigId == item1.id">
                <div v-if="item1.minSize == 0">
                  <span v-if="item1.maxSize == 0">不限</span>
                  <span v-else>小于等于{{ item1.maxSize }}</span>
                </div>
                <div v-else>{{ item1.minSize }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="文件模板">
          <template #default="scope">
            <div
              class="table_file"
              v-if="scope.row.templateFileName != ''"
              @click="
                download_file({
                  url: scope.row.templateFileUrl,
                  fileName: scope.row.templateFileName,
                })
              "
            >
              {{ scope.row.templateFileName }}
            </div>
            <div v-else>无</div>
          </template>
        </el-table-column>
        <el-table-column label="操作记录">
          <template #default="scope">
            <el-button
              @click="expandChange(scope.row, [scope.row])"
              v-if="scope.row.recordList?.length"
              >查看 <span>({{ scope.row.recordList.length }})</span>
            </el-button>

            <div v-else>无</div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          v-if="(node_index == 3 && item_form_data.status == 3) || node_index != 3"
        >
          <template #default="scope">
            <div
              class="flex_cc"
              v-if="
                !scope.row.isSeparateRoute ||
                (scope.row.isSeparateRoute && has_role_list[1].has_role)
              "
            >
              <el-button
                @click="
                  show_table_upload_box({
                    item: scope.row,
                    sourceId: item.id ? item.id : '',
                  })
                "
              >
                <span v-if="scope.row.url == ''">上传</span>
                <span v-else>更新</span>
              </el-button>
              <el-button v-if="scope.row.fileName != ''" @click="delete_file(scope.row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-dialog v-model="table_upload_box" title="提示" width="30%" destory-on-close>
    <span style="padding-left: 20px"
      >上传及更新为最新版本文件<span v-if="table_upload_item.url != ''"
        >，原有文件则成为历史版本</span
      >。</span
    >
    <el-divider style="margin-top: 30px"></el-divider>
    <template #footer>
      <div class="flex" style="justify-content: flex-end">
        <el-button class="m_right10" @click="table_upload_box = false">取消</el-button>
        <upload
          :imageUrl="table_upload_item.table_upload_url"
          :width="100"
          :height="100"
          :limit="table_upload_item.limit"
          :minSize="table_upload_item.minSize"
          :maxSize="table_upload_item.maxSize"
          :accept="table_upload_item.accept"
          :fileNames="table_upload_item.table_upload_fileName"
          :upload_btn="true"
        ></upload>
      </div>
    </template>
  </el-dialog>
  <div v-if="type != 5 && node_item?.type == type">
    <div v-for="(item1, index1) in node_item?.file_data">
      <div>
        文件资料名称：
        <span class="c_3580eb">{{ item1.name }}</span> (数量：{{
          item1.limit
        }}
        )、(格式：{{ item1.accept }} )、(大小：<span
          v-if="item1.minSize <= 0 && item1.maxSize <= 0"
          >不限</span
        >
        <span v-if="item1.minSize <= 0 && item1.maxSize > 0">
          小于 {{ item1.maxSize }} M</span
        >
        <span v-if="item1.minSize > 0 && item1.maxSize > 0"
          >{{ item1.minSize }} M - {{ item1.maxSize }} M</span
        >)
      </div>
      <div class="m_20_0 m_left20">
        <div>模板文件<span v-if="item1.template_url == ''">(无)</span></div>
        <div v-if="item1.template_url != ''">
          <div
            class="p_rel m_right10"
            style="width: 100px; height: 100px"
            @mouseenter="down_index = index1"
            @mouseleave="down_index = -1"
          >
            <div
              v-show="down_index == index1"
              class="down_icon flex_cc"
              @click="
                download_file({
                  url: item1.template_url,
                  fileName: item1.template_fileName,
                })
              "
            >
              <el-icon :size="30" color="#777"><Download /></el-icon>
            </div>
            <img
              src="@/assets/img/file_default.png"
              style="width: 100px; height: 100px"
            />
          </div>
          <p>{{ item1.template_fileName }}</p>
        </div>

        <div class="m_top10">
          <div>项目文件</div>
          <upload
            :imageUrl="item1.url"
            :width="100"
            :height="100"
            :limit="item1.limit"
            :minSize="item1.minSize"
            :maxSize="item1.maxSize"
            :accept="item1.accept"
            :fileNames="item1.fileName"
          ></upload>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { formatDate, handle_search_key, check_role } from "@/utils/check_role"; // 权限校验
import { ref, toRefs, onMounted } from "vue";
import upload from "@/view/components/upload.vue";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
const store = useStore();
const props = defineProps({
  item_form_data: Object,
  type: Number,
  isAdd: Boolean,
  sourceId: {
    type: String,
    defaulr: "",
  },
});
const has_role_list = ref([
  { path: "isSeparateRoute", has_role: false },
  { path: "isSeparateRoute/put", has_role: false },
]);
const type_list = ref();
const get_node_list = () => {
  axios
    .request({
      url: serviceApi.nodeConfig + "/list",
      method: "post",
      data: handle_search_key({ enterpriseId: store.state.enterprise_id }),
    })
    .then((res) => {
      console.log(res);
      res.data.forEach((i, index) => {
        i.label = i.nodeName;
        i.value = index + 1;
      });
      type_list.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const { item_form_data, isAdd, type, sourceId } = toRefs<any>(props);
const node_index = ref(0);
const down_index = ref();
const node_list = ref([]);
const node_item = ref<any>();
onMounted(() => {
  node_list.value = [];
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item);
  });
  console.log(item_form_data.value);
  get_file_list();
  get_node_list();
  EventBus.on("upload_succ", () => {
    console.log(node_list.value);
    if (type.value != 5) {
      EventBus.emit("uploadFile", node_list.value);
    } else {
      if (!table_upload_item.value?.table_upload_fileName?.length) return;
      let data = {
        fileConfigId: table_upload_item.value.fileConfigId,
        fileName: table_upload_item.value.table_upload_fileName[0],
        taskId: item_form_data.value.id,
        type: node_index.value + 1,
        url: table_upload_item.value.table_upload_url[0],
        sourceId: sourceId.value,
      };
      console.log(data);
      table_upload(data);
    }
  });
  get_requireChange_list();
  get_taskOrder_list();
  node_index.value = 0;
  EventBus.on("change_serviceEnterpriseId", () => {
    get_serviceEnterprise_list();
  });
});
const expands = ref([]);
const expandChange = (e, expandedRows) => {
  console.log(e, expandedRows);
  if (expandedRows.length) {
    if (e) {
      if (expands.value.includes(e.id)) {
        expands.value = expands.value.filter((i) => {
          return i != e.id;
        });
      } else {
        expands.value.push(e.id); // 每次push进去的是每行的ID
      }
    }
  } else {
    expands.value = []; // 默认不展开
  }
  if (!expands.value.length) return;
};
const delete_file = (e) => {
  console.log(e);
  ElMessageBox.confirm("确定删除该节点文件", "", {
    closeOnClickModal: false,
    type: "warning",
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.taskFile + "/" + e.id,
          method: "delete",
        })
        .then(() => {
          ElMessage.success("操作成功！");
          setTimeout(() => {
            get_task_file_list();
          }, 1000);
        });
    })
    .catch(() => {});
};
// const sourceId = ref("");
const show_table_upload_box = (e) => {
  console.log(e, task_file_list.value);
  let file_item = file_list.value.find((i) => i.id == e.item.fileConfigId);
  console.log(file_item);
  table_upload_item.value = e.item;
  table_upload_item.value.accept = file_item.fileTypeList;
  table_upload_item.value.maxSize = file_item.maxSize;
  table_upload_item.value.minSize = file_item.minSize;
  table_upload_item.value.limit = 1;
  sourceId.value = e.sourceId;
  table_upload_box.value = true;
  console.log(e, task_file_list.value);
};
const table_upload_box = ref(false);
const table_upload_item = ref();
const table_upload = (data) => {
  axios
    .request({
      url:
        serviceApi.taskFile +
        (table_upload_item.value.url == "" ? "" : "/" + table_upload_item.value.id),
      method: table_upload_item.value.url == "" ? "post" : "put",
      data: data,
    })
    .then(() => {
      ElMessage.success("操作成功！");
      setTimeout(() => {
        table_upload_box.value = false;
        table_upload_item.value.table_upload_fileName = [];
        table_upload_item.value.table_upload_url = [];
        get_task_file_list();
      }, 1000);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const get_serviceEnterprise_list = () => {
  axios
    .request({
      url: serviceApi.nodeConfig + "/file/list",
      method: "post",
      data: {
        serviceEnterpriseId: item_form_data.value.serviceEnterpriseId,
      },
    })
    .then((res) => {
      console.log(res);
      res.data.forEach((i) => {
        i.file_data = [];
        file_list.value.forEach((ii) => {
          if (i.fileConfigId.includes(ii.id)) {
            i.file_data.push({
              id: ii.id,
              name: ii.name,
              accept: ii.fileTypeList,
              limit: ii.maxFileNum,
              minSize: ii.minSize,
              maxSize: ii.maxSize,
              template_url: "",
              template_fileName: "",
              url: [],
              fileName: [],
              recordList: [],
              table_upload_fileName: [],
              table_upload_url: [],
              updateTime: "",
              createByName: "",
              isSeparateRoute: ii.isSeparateRoute,
            });
          }
        });
      });
      node_list.value =
        type.value == 5
          ? res.data
          : res.data.filter((i) => {
              return i.type == type.value;
            });
      node_item.value = node_list.value[0];
      //   console.log(res.data, node_list.value, file_list.value);
      get_node_file_template_list();
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
// 服务企业配置模板文件
const get_node_file_template_list = () => {
  axios
    .request({
      url: serviceApi.serviceEnterprise_fileConfigTemplate + "/list",
      method: "post",
      data: {
        enterpriseId: store.state.enterprise_id,
        serviceEnterpriseId: item_form_data.value.serviceEnterpriseId,
      },
    })
    .then((res) => {
      node_list.value.forEach((i) => {
        res.data.forEach((ii) => {
          i.file_data.forEach((iii) => {
            if (iii.id == ii.fileConfigId) {
              iii.template_fileName = ii.fileName;
              iii.template_url = ii.url;
            }
          });
        });
      });
      if (node_list.value?.length && !isAdd.value) {
        setTimeout(() => {
          get_task_file_list();
        }, 200);
      } else {
        node_list.value.forEach((i) => {
          i.file_data.forEach((ii) => {
            ii.url = [];
            ii.fileName = [];
          });
        });
      }
      //   console.log(node_list.value, isAdd.value);
      EventBus.emit("uploadFile", node_list.value);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
// 项目已上传的文件列表
const task_file_list = ref([]);
const get_task_file_list = () => {
  axios
    .request({
      url: serviceApi.taskFile + "/list",
      method: "post",
      data: { taskId: item_form_data.value.id },
    })
    .then((res) => {
      //   console.log(res);
      if (node_index.value == 0) {
        node_item.value.file_data.forEach((i) => {
          res.data.forEach((ii) => {
            if (ii.sourceId == sourceId.value && i.id == ii.fileConfigId) {
              //   console.log(sourceId.value, i, ii);
              i.url = ii.url != "" ? ii.url.split(",") : [];
              i.fileName = ii.fileName != "" ? ii.fileName.split(",") : [];
            }
          });
          let has_file = res.data.some((ii) => {
            return ii.fileConfigId == i.id;
          });
          if (!has_file) {
            let obj = {
              createByName: "",
              fileName: "",
              url: "",
              id: "",
              fileConfigId: i.id,
              name: i.name,
              accept: i.fileTypeList,
              limit: i.maxFileNum,
              minSize: i.minSize,
              maxSize: i.maxSize,
              recordList: [],
              table_upload_fileName: [],
              table_upload_url: [],
              templateFileName: i.template_fileName,
              templateUrl: i.template_url,
              updateTime: "",
              type: 1,
              isSeparateRoute: i.isSeparateRoute,
            };
            res.data.push(obj);
          }
        });
      }
      res.data.forEach((i) => {
        i.table_upload_fileName = [];
        i.table_upload_url = [];
        if (i.recordList.length) {
          i.recordList = i.recordList.reverse();
        }
      });
      task_file_list.value = res.data;
      console.log(node_item.value, node_list.value);
      if (!isAdd.value) {
        EventBus.emit("uploadFile", node_list.value);
      }
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};

// 文件资料配置列表
const file_list = ref([]);
const get_file_list = () => {
  axios
    .request({
      url: serviceApi.projectInformation + "/list",
      method: "post",
      data: handle_search_key({ enterpriseId: store.state.enterprise_id }),
    })
    .then((res) => {
      console.log(res);
      file_list.value = res.data;

      get_serviceEnterprise_list();
      console.log(node_list.value);
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const download_file = (e) => {
  download_fun(e);
};
const download_fun = (e) => {
  //   window.open(e);
  console.log(e);
  let http = new XMLHttpRequest();
  http.open("GET", e.url, true);
  http.responseType = "blob";
  http.onload = function () {
    const url = window.URL.createObjectURL(http.response);
    const a = document.createElement("a");
    a.href = url;
    a.download = e.fileName;
    a.click();
  };
  http.send();
  return;
  axios
    .request({
      url: serviceApi.download + "/" + e,
      method: "get",
      responseType: "blob",
    })
    .then((res1) => {
      console.log(res1);
      const blob = new Blob([res1 as any]); // res.data 为接口返回的数据，依实例而行
      const URL = window.URL.createObjectURL(blob); // 生成一个 Blob URL
      const fileName = e.item1.template_fileName[e.index2]; // 文件名+后缀
      const listNode = document.createElement("a");
      listNode.download = fileName as any;
      listNode.style.display = "none";
      listNode.href = URL; // 文件流生成的url
      document.body.appendChild(listNode);
      listNode.click(); // 模拟在按钮上实现一次鼠标点击
      window.URL.revokeObjectURL(listNode.href); // 释放 URL 对象
      document.body.removeChild(listNode); // 移除 a 标签
    });
};
// 需求列表
const requireChange_list = ref([]);
const get_requireChange_list = () => {
  axios
    .request({
      url: serviceApi.taskChange + "/list",
      method: "post",
      data: {
        taskId: item_form_data.value.id,
        statusList: [2, 4],
      },
    })
    .then((res) => {
      console.log(res);
      requireChange_list.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
// 下单记录
const taskOrder_list = ref([]);
const get_taskOrder_list = () => {
  axios
    .request({
      url: serviceApi.taskOrder + "/list",
      method: "post",
      data: {
        taskId: item_form_data.value.id,
      },
    })
    .then((res) => {
      console.log(res);
      taskOrder_list.value = res.data;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog__header) {
  background-color: #fff !important;
}
:deep(.el-dialog__title) {
  color: #333 !important;
}
:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #333 !important;
}
.table_file {
  color: #3580eb;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}
.top_title {
  width: 100px;
  display: flex;
  align-items: center;
  padding: 5px 0;
  margin: 10px;
  justify-content: center;
  border: 1px solid #000;
  border-radius: 2px;
  font-size: 16px;
  cursor: pointer;
  &:hover {
    border-color: #3580eb;
    color: #3580eb;
  }
}
.top_title_select {
  border-color: #3580eb;
  color: #3580eb;
}
.select_me {
  transform: rotate(90deg);
}
.down_icon {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  background: rgba(0, 0, 0, 0.1);
  cursor: pointer;
}
.border {
  border: 1px solid #ccc;
}
.delete_icon {
  cursor: pointer;
  position: absolute;
  right: 4px;
  top: 4px;
  z-index: 101;
}
</style>
